package org.teremail.client;

import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.FlexTable;

public class FolderController {

    private final FlexTable view;
    private final ErrorHandler errorHandler;
    private final MailServiceAsync service;
    private String mailboxName;
    private String[] folderNames;
    private TableSelectionListener selection;

    public FolderController(FlexTable ft, ErrorHandler errorHandler,
            MailServiceAsync service) {
        this.view = ft;
        this.errorHandler = errorHandler;
        this.service = service;
        
        init();
    }

    private void init() {
        view.setText(0, 0, "Folders");
        view.getCellFormatter().addStyleName(0, 0, "header");
        view.setWidth("6em");
        view.addStyleName("bordered");

        setFolders(new String[0]);
        selection = TableSelectionListener.create(view, new int[] {0});
        view.addTableListener(selection);
    }
    
    private void setFolders(String[] folderNames) {
        
        this.folderNames = folderNames;
        
        if (folderNames.length > 0) {
            for (int i = 0; i < folderNames.length; i++) {
                view.setText(i+1, 0, folderNames[i]);
                view.getCellFormatter().addStyleName(i+1, 0, "mousePointer");
            }
        } else {
            view.setText(1, 0, "Loading...");
        }
    }

    public void fetchFolders(String mailboxName) {
        this.mailboxName = mailboxName;
        service.getFolders(mailboxName, new AsyncCallback<String[]>() {
            public void onFailure(Throwable caught) {
                errorHandler.showMessage(caught.getMessage());
            }

            public void onSuccess(String[] folderNames) {
                setFolders(folderNames);
            }
        });
        
    }
    
    public String getMailbox() {
        return mailboxName;
    }

}
